package net.qqxh.service.task;

import net.qqxh.common.utils.FileAnalysisTool;
import net.qqxh.persistent.Jfile;
import net.qqxh.persistent.SearchLib;
import net.qqxh.resolve2text.exception.File2TextResolveException;
import net.qqxh.resolve2view.exception.File2ViewResolveException;
import net.qqxh.service.FileResolveService;


import net.qqxh.service.model.ResolveCallBackMsg;
import org.apache.commons.io.FileUtils;
import org.joda.time.field.FieldUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
public class FileResolveTask {
    @Autowired
    FileResolveService fileResolveService;

    private final static Logger logger = LoggerFactory.getLogger(FileResolveTask.class);

    @Async("fileResolveExecutor")
    public void doFileResolve(SearchLib searchLib, Jfile file, FileResolveTaskCallBack fileResolveTaskCallBack, Integer totalCount, Integer nowCount) throws IOException {
        Thread th = Thread.currentThread();
        logger.info(System.currentTimeMillis() + "................." + th.getId() + ".................." + th.getName());
        long start = System.currentTimeMillis();
        String path = file.getPath();
        ResolveCallBackMsg msg = new ResolveCallBackMsg();
        msg.setTotalCount(totalCount);
        msg.setIndex(nowCount);
        msg.setLevel("info");
        int fileResolveStatus = 0;
        try {
            fileResolveService.resolve(searchLib, file);
            long end = System.currentTimeMillis();
            String str = "转换文件==《" + path + "'》==成功，耗时：" + (end - start) + "毫秒";
            logger.info(str);
            msg.setLevel("info");
            msg.setMsg(str);
        } catch (File2TextResolveException e) {
            long end = System.currentTimeMillis();
            setFailMsg(path, end - start, msg, e);
            fileResolveStatus += 1;
        } catch (File2ViewResolveException e) {
            long end = System.currentTimeMillis();
            setFailMsg(path, end - start, msg, e);
            fileResolveStatus += 2;
        } catch (Exception e) {
            fileResolveStatus += 3;
            long end = System.currentTimeMillis();
            setFailMsg(path, end - start, msg, e);
        } finally {
            if (fileResolveStatus > 0) {
                /*保存处理异常文件*/
                savaFailFile(searchLib, file, fileResolveStatus);
            }
        }
        if (fileResolveTaskCallBack != null) {
            if (nowCount.equals(totalCount)) {
                msg.setFinish(true);
            } else {
                msg.setFinish(false);
            }
            fileResolveTaskCallBack.doCallBack(msg);
        }

    }

    private void setFailMsg(String path, Long time, ResolveCallBackMsg msg, Exception e) {
        String str = "转换文件==《" + path + "'》==失败，耗时：" + time + "毫秒";
        msg.setMsg(str);
        msg.setLevel("warn");
        logger.warn(str, e);
    }

    private void savaFailFile(SearchLib searchLib, Jfile file, int fileResolveStatus) {
        File srcDir = new File(searchLib.getFileSourceDir());
        String path = file.getPath();
        String failPath = FileAnalysisTool.replaceFirst(path, srcDir.getPath(), srcDir.getPath() + "_fail");
        try {
            FileUtils.copyFile(new File(path), new File(failPath));
        } catch (IOException e) {
            logger.info("{}", e.fillInStackTrace());
        }
    }

}
